import pygame
import sys
import random
import loading
import moviepy.editor as mp

def play_video_in_game_loop():
    # 初始化 Pygame
    pygame.init()

    # 加载视频
    clip = mp.VideoFileClip('./img/800-500mp4.mp4')

    # 设置屏幕大小为视频大小
    screen = pygame.display.set_mode(clip.size)
    clock = pygame.time.Clock()

    # 获取视频总时长
    video_duration = clip.duration

    # 播放视频
    start_time = pygame.time.get_ticks()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                    return  # 跳过视频并进入游戏

        # 计算当前时间点
        current_time = (pygame.time.get_ticks() - start_time) / 1000.0

        # 如果视频播放完毕，则退出循环
        if current_time > video_duration:
            break

        # 获取当前帧
        img = clip.get_frame(current_time)
        pygame_img = pygame.image.frombuffer(img.tobytes(), img.shape[1::-1], "RGB")

        # 显示当前帧
        screen.blit(pygame_img, (0, 0))
        pygame.display.update()
        clock.tick(clip.fps)
# 角色类
class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = loading.player_image
        self.rect = self.image.get_rect(center=(loading.SCREEN_WIDTH // 2, loading.SCREEN_HEIGHT // 2))
        self.speed = 5

    def update(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            self.rect.x -= self.speed
        if keys[pygame.K_RIGHT]:
            self.rect.x += self.speed
        if keys[pygame.K_UP]:
            self.rect.y -= self.speed
        if keys[pygame.K_DOWN]:
            self.rect.y += self.speed

        # 确保玩家不会移出屏幕
        if self.rect.left < 0:
            self.rect.left = 0
        if self.rect.right > loading.SCREEN_WIDTH:
            self.rect.right = loading.SCREEN_WIDTH
        if self.rect.top < 0:
            self.rect.top = 0
        if self.rect.bottom > loading.SCREEN_HEIGHT:
            self.rect.bottom = loading.SCREEN_HEIGHT


# 闪电类
class Lightning(pygame.sprite.Sprite):
    def __init__(self, image1, image2, x, y):
        super().__init__()
        self.image1 = image1
        self.image2 = image2
        self.image = self.image1
        self.rect = self.image.get_rect()
        self.rect.topleft = (x, y)
        self.spawn_time = pygame.time.get_ticks()  # 记录闪电出现的时间
        self.second_stage = False
        self.dead = False

    def update(self):
        now = pygame.time.get_ticks()
        if not self.second_stage and now - self.spawn_time > 2000:
            self.image = self.image2
            # 更新矩形，并保持顶部左侧位置相同
            old_topleft = self.rect.topleft
            self.rect = self.image.get_rect()
            self.rect.topleft = old_topleft
            self.second_stage = True
        if now - self.spawn_time > 3000:
            self.kill()
            self.dead = True

class Enemy1(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = loading.enemy_img1
        self.rect = self.image.get_rect()
        self.rect.x = loading.SCREEN_WIDTH-170
        self.rect.y = random.randint(0, loading.SCREEN_HEIGHT - self.rect.height)
        self.speed = random.randint(3, 6)

    def update(self):
        self.rect.x -= self.speed
        if self.rect.right < 0:
            self.kill()  # Remove the enemy when it goes off-screen


class Fireball(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = loading.fireball_img
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
        self.speed = 10

    def update(self):
        self.rect.x += self.speed
        if self.rect.left > loading.SCREEN_WIDTH:
            self.kill()  # Remove the fireball when it goes off-screen



class Bomb(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = loading.bomb_img
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
        self.gravity = 1
        self.speed_x = random.randint(-10, -7  )
        self.speed_y = random.randint(-15, -10)

    def update(self):
        self.rect.x += self.speed_x
        self.rect.y += self.speed_y
        self.speed_y += self.gravity

        if self.rect.bottom >= loading.SCREEN_HEIGHT or self.rect.right <= 0:
            self.explode()  # Explode when touching the ground or going off-screen
            self.kill()

    def explode(self):
        explosion = Explosion(self.rect.centerx, self.rect.centery)
        all_sprites.add(explosion)


class Explosion(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = loading.explosion_img
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
        self.duration = 30
        self.frame_count = 0
        loading.bz_s.play()
    def update(self):
        self.frame_count += 1
        if self.frame_count >= self.duration:
            self.kill()


class Enemy2(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.frames = []
        for i in range(loading.enemy2_gif.get_rect().width // loading.enemy2_gif.get_rect().height):
            frame = loading.enemy2_gif.subsurface(pygame.Rect(
                i * loading.enemy2_gif.get_rect().height, 0, loading.enemy2_gif.get_rect().height, loading.enemy2_gif.get_rect().height))
            self.frames.append(frame)
        self.current_frame = 0
        self.image = self.frames[self.current_frame]
        self.rect = self.image.get_rect()
        self.rect.x = loading.SCREEN_WIDTH
        self.rect.y = random.randint(0, loading.SCREEN_HEIGHT - self.rect.height)
        self.animation_speed = 0.1
        self.frame_time = 0
        self.last_bomb_time = pygame.time.get_ticks()
        self.spawn_time = pygame.time.get_ticks()
        self.health = 3  # 设置敌人2号的生命值
        self.shoot_delay = 2000  # 发射箭矢的间隔时间（毫秒）
        self.last_shot = pygame.time.get_ticks()

    def shoot_arrow(self):
        now = pygame.time.get_ticks()
        if now - self.last_shot >= self.shoot_delay:
            self.last_shot = now
            arrow = Arrow()  # 创建箭矢对象
            arrow.rect.x = self.rect.x
            arrow.rect.y = self.rect.y + self.rect.height // 2 - arrow.rect.height // 2
            all_sprites.add(arrow)  # 将箭矢添加到精灵组中
            arrows.add(arrow)  # 将箭矢添加到箭矢精灵组中

    def update(self):
        self.shoot_arrow()
        self.frame_time += self.animation_speed
        if self.frame_time >= 1:
            self.frame_time = 0
            self.current_frame = (self.current_frame + 1) % len(self.frames)
            self.image = self.frames[self.current_frame]

        # 每隔一段时间丢一次炸弹
        current_time = pygame.time.get_ticks()
        if current_time - self.spawn_time > 2000:  # 在出现2秒后开始投掷炸弹
            if current_time - self.last_bomb_time > random.randint(2000, 5000):
                bomb = Bomb(self.rect.centerx, self.rect.centery)
                bombs.add(bomb)
                all_sprites.add(bomb)
                self.last_bomb_time = current_time

        self.rect.x -= 2  # 移动敌人2号
        if self.rect.right < 0:
            self.kill()  # 移除敌人当它离开屏幕时

class Enemy3(pygame.sprite.Sprite):
    def __init__(self, enemy_img):
        super().__init__()
        self.image = enemy_img
        self.rect = self.image.get_rect()
        self.rect.x = loading.SCREEN_WIDTH
        self.rect.y = random.randint(50, loading.SCREEN_HEIGHT - 100)
        self.spawn_time = pygame.time.get_ticks()  # 初始化生成时间
        self.attack_time = self.spawn_time  # 初始化攻击时间

    def update(self):
        # 移动敌人3的位置
        self.rect.x -= 2
        if self.rect.x < -self.rect.width:
            self.kill()


class Arrow(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.image.load('./img/arrow.png').convert_alpha()  # 加载箭矢素材图片
        self.rect = self.image.get_rect()
        self.speed = 5  # 箭矢水平运动的速度
        loading.js_s.play()
    def update(self):
        self.rect.x -= self.speed  # 箭矢水平向左运动

        # 检测箭矢是否与角色碰撞
        if pygame.sprite.spritecollide(self,player_group, True):
            print("Player hit by arrow! Game Over.")
            pygame.quit()
            sys.exit()


class Background:
    def __init__(self):
        self.image = loading.background_img
        self.rect = self.image.get_rect()
        self.x1 = 0
        self.x2 = self.rect.width

    def update(self):
        self.x1 -= 2
        self.x2 -= 2
        if self.x1 <= -self.rect.width:
            self.x1 = self.rect.width
        if self.x2 <= -self.rect.width:
            self.x2 = self.rect.width

    def draw(self, screen):
        screen.blit(self.image, (self.x1, 0))
        screen.blit(self.image, (self.x2, 0))



class Timer:
    def __init__(self, max_time=30):
        self.max_time = max_time
        self.current_time = max_time
        self.font = pygame.font.Font(None, 36)
        self.color = loading.WHITE
        self.timer_text = self.font.render(f"Time: {self.current_time}", True, self.color)
        self.timer_rect = self.timer_text.get_rect()
        self.timer_rect.bottomleft = (10, loading.SCREEN_HEIGHT - 10)

    def update(self):
        self.current_time -= 1 / 60  # Decrease time based on frame rate
        if self.current_time < 0:
            self.current_time = 0

        # Change color to RED if time is less than 10
        if self.current_time < 10:
            self.color = loading.RED
        else:
            self.color = loading.WHITE

        self.timer_text = self.font.render(f"Time: {int(self.current_time)}", True, self.color)

    def add_time(self, extra_time):
        self.current_time += extra_time
        if self.current_time > self.max_time:
            self.current_time = self.max_time
        self.timer_text = self.font.render(f"Time: {int(self.current_time)}", True, self.color)

    def draw(self, screen):
        screen.blit(self.timer_text, self.timer_rect)


class GameOver:
    def __init__(self):
        self.image = pygame.image.load('./img/game_over.png')
        self.rect = self.image.get_rect()
        self.rect.center = (loading.SCREEN_WIDTH // 2, loading.SCREEN_HEIGHT // 2)
    def draw(self, screen):
        loading.BGM.stop()
        loading.end_s.play()
        screen.blit(self.image, self.rect)




# 道具类
class Prop(pygame.sprite.Sprite):
    def __init__(self, image):
        super().__init__()
        self.image = image
        self.rect = self.image.get_rect()
        self.rect.x = loading.SCREEN_WIDTH  # 道具初始位置在屏幕右侧
        self.rect.y = random.randint(0, loading.SCREEN_HEIGHT - self.rect.height)  # 随机出现在屏幕内的位置
        self.speed = 3  # 道具移动速度

    def update(self):
        # 移动道具
        self.rect.x -= self.speed


# 创建玩家实例
player = Player()
all_sprites = pygame.sprite.Group()
player_group = pygame.sprite.GroupSingle(player)
all_sprites.add(player)
# 创建敌人组和火球组闪电组
lightning_group = pygame.sprite.Group()
enemies1 = pygame.sprite.Group()
enemies2 = pygame.sprite.Group()
fireballs = pygame.sprite.Group()
bombs = pygame.sprite.Group()
arrows = pygame.sprite.Group()
enemies3 = pygame.sprite.Group()
props_group = pygame.sprite.Group()
# 创建背景实例
background = Background()

# 创建计时器实例和结算界面实例
timer = Timer()
game_over_screen =GameOver()